package xcmg.device.service.userinfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.device.infra.ExportUtil;
import yb.ecp.fast.dto.ProfileDTO;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.infra.infra.ActionResult;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private AuthClient authClient;

    @Autowired
    private HttpServletResponse response;

    public void export(String[] userids) throws Exception {
        ActionResult<List<ProfileDTO>> actionResult = authClient.listByIds(userids);
        List<ProfileDTO> list = actionResult.getValue();
        invokeExport(list);

    }

    public void exportAll(ProfileDTO condition, String userId) throws Exception {
        ActionResult<List<ProfileDTO>> actionResult = authClient.list4export(condition, userId);
        List<ProfileDTO> list = actionResult.getValue();
        invokeExport(list);
    }

    private void invokeExport(List<ProfileDTO> list) throws Exception {
        String title = "用户数据导出";
        String[] rowsName = new String[]{"用户账号", "用户名", "SAP编码", "昵称", "性别", "状态", "联系电话", "手机号", "所属部门", "电子邮箱", "最后登录时间"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (ProfileDTO profileDTO : list) {
            objs = new Object[rowsName.length];
            objs[0] = profileDTO.getLoginName();
            objs[1] = profileDTO.getName();
            objs[2] = profileDTO.getSapCode();
            objs[3] = profileDTO.getNickname();
            objs[4] = getSexDesc(profileDTO.getSex());
            objs[5] = getLockedDesc(profileDTO.getLocked());
            objs[6] = profileDTO.getTelephone();
            objs[7] = profileDTO.getMobile();
            objs[8] = profileDTO.getDeptName();
            objs[9] = profileDTO.getEmail();
            objs[10] = profileDTO.getLastLoginTime() == null ? "" : sdf.format(profileDTO.getLastLoginTime());
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response, null);
    }

    private String getSexDesc(Integer sex) {
        if (sex == null) {
            return "女";
        }
        switch (sex) {
            case 0:
                return "女";
            case 1:
                return "男";
            default:
                return "";
        }
    }

    private String getLockedDesc(Integer locked) {
        if (locked == null) {
            return "启用";
        }
        switch (locked) {
            case 0:
                return "启用";
            case 1:
                return "锁定";
            default:
                return "";
        }
    }
}
